/******************************************************/
/* Goblin's Cube - Rubik's cube game for Wii Homebrew */
/* Copyright (C) 2009 Ricardo Bueno Cordeiro          */
/* Licensed under de GNU General Public License v2.0  */
/*   See license_gplv2.txt for detalis                */
/******************************************************/

#include <gccore.h>

#include "draw.h"
#include "control_highscore.h"
#include "cube.h"

ControlHighscore::ControlHighscore() : local("Local highscore"), online("Online highscore") {
	this->local.load_local();
	this->naming_result = -1;
}

int ControlHighscore::update(WPADData *wiimote_data, int state) {
	if (state != CONTROL_FOREGROUND)
		return 0;
		
	if (this->naming_result < 0) {
		if (wiimote_data->btns_d & WPAD_BUTTON_A)
			Cube::cube.scramble();
	} else {
		if (wiimote_data->btns_d & WPAD_BUTTON_LEFT)
			this->naming_current_letter = (this->naming_current_letter + 2) % 3;
		if (wiimote_data->btns_d & WPAD_BUTTON_RIGHT)
			this->naming_current_letter = (this->naming_current_letter + 1) % 3;

		if (wiimote_data->btns_d & WPAD_BUTTON_UP) {
			u8 c = this->local.get_char(this->naming_result, this->naming_current_letter);
			c = ((c - 'A' + 1) % 26) + 'A';
			this->local.set_char(this->naming_result, this->naming_current_letter, c);
		}
		if (wiimote_data->btns_d & WPAD_BUTTON_DOWN) {
			u8 c = this->local.get_char(this->naming_result, this->naming_current_letter);
			c = ((c - 'A' + 25) % 26) + 'A';
			this->local.set_char(this->naming_result, this->naming_current_letter, c);
		}

		if (wiimote_data->btns_d & WPAD_BUTTON_A) {
			this->local.save_local();
			this->local.send_online(this->naming_result, &this->online);
			this->naming_result = -1;
		}
	}

	return 0;
}

void ControlHighscore::draw(int state) {
	if (state != CONTROL_FOREGROUND)
		return;
}

void ControlHighscore::text(int state) {
	if (state != CONTROL_FOREGROUND)
		return;

	local.draw_board(80, 832, this->naming_result, this->naming_current_letter);
	online.draw_board(550, 832, -1, 0);

	if (this->naming_result < 0)
		DR_draw_text(500, 80, (GXColor){ 255, 255, 255, 255}, FTGX_JUSTIFY_CENTER, "Press A to start a new game");
	else {
		DR_draw_text(500, 100, (GXColor){ 255, 255, 255, 255}, FTGX_JUSTIFY_CENTER, "Use the DIRECTION PAD to select your initials,");
		DR_draw_text(500, 68, (GXColor){ 255, 255, 255, 255}, FTGX_JUSTIFY_CENTER, "then press A to save your score");
	}
}

void ControlHighscore::just_solved() {
	int result = local.add_score("AAA", Cube::cube.get_current_time());
	this->online.load_online();
	
	if (result < 0)
		return;

	this->naming_result = result;	
	this->naming_current_letter = 0;
}
